/*
 * @Descripttion: 二次封装 axios 请求 多数中小公司并没有那么高的要求 所以不做单点登录就没必要整 刷新token 这回事
 * @version:
 * @Author: lhl
 * @Date: 2024-10-23 14:35:47
 * @LastEditors: lhl
 * @LastEditTime: 2024-10-25 10:04:13
 */
import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { message } from 'antd';

interface ApiResponse<T = unknown> {
  code: number;
  msg: string;
  data: T;
}

const instance: AxiosInstance = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    if (response.status === 200 && response.data.code === 200) {
      return response.data;
    } else {
      message.error(`${response.data.msg}`);
      return Promise.reject(new Error(`请求失败，状态码: ${response.status}`));
    }
  },
  (error) => {
    message.error('请求失败');
    if (!window.navigator.onLine) {
      message.error('网络连接已断开，请检查网络设置');
    }
    return Promise.reject(error);
  }
);

export default instance;
